import Axios from 'axios';
import Qs from 'qs';
import { Toast } from 'vant';
let loading = null;
Axios.create({
  timeout: 50 * 1000
});
function clearLoading() {
  if (loading) {
    loading.clear();
    loading = null;
  }
}
// 请求拦截器
Axios.interceptors.request.use(
  (config) => {
    try {
      if (config['headers']['loading']) {
        loading = Toast.loading({
          duration: 0,
          icon: require('@/assets/images/loading.webp'),
          className: 'yui-loading',
          forbidClick: true
        });
      }
    } catch (e) {
      console.log(e);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 添加响应拦截器
Axios.interceptors.response.use(
  function (response) {
    clearLoading();
    return response;
  },
  function (error) {
    clearLoading();
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

// 字符串参数请求啊
export const AxiosApi = (url, data = {}, type = 'post', params = {}, loading = false) => {
  return new Promise((resolve, reject) => {
    Axios({
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        loading: loading
      },
      transformRequest: [
        (data) => {
          data = Qs.stringify(data);
          return data;
        }
      ],
      method: type,
      url: url,
      data: data,
      params: params
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
};
// json参数请求
export const AxiosJsonApi = (url, data = {}, type = 'post', params = {}, loading = false) => {
  return new Promise((resolve, reject) => {
    Axios({
      headers: {
        'Content-Type': 'application/json',
        loading: loading
      },
      transformRequest: [
        (data) => {
          data = JSON.stringify(data);
          return data;
        }
      ],
      method: type,
      url: url,
      data: data,
      params: params
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
};
